package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"shopes/srv/model/mysql"
	"shopes/srv/pkg"
	"strconv"

	"shopes/srv/internal/svc"
	"shopes/srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *shop.OrderAddRequest) (*shop.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Good{}
	err := g.GetGood(int(in.GoodId))
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if g.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	newString := uuid.NewString()

	o := mysql.Order{
		UserId:     int(in.UserId),
		OrderSn:    newString,
		GoodId:     int(in.GoodId),
		Amount:     g.GoodsPrice,
		Status:     int(in.Status),
		Payment:    2,
		GoodsTitle: g.GoodsTitle,
		GoodsCover: g.GoodsCover,
	}
	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	goodsStock := g.GoodsStock - 1
	err = g.UpdateStock(goodsStock)
	if err != nil {
		return nil, fmt.Errorf("库存更新失败")
	}
	float := strconv.FormatFloat(g.GoodsPrice, 'f', 2, 64)
	pay := pkg.NewAliPay()
	Url := pay.Pay(g.GoodsTitle, newString, float)
	return &shop.OrderAddResponse{
		OrderSn: newString,
		Key:     Url,
	}, nil
}
